package com.StarStudio.Controller;

import com.StarStudio.Service.*;
import com.ruoyi.common.core.Entity.*;
import com.StarStudio.Utils.QueryPageUtils;
import com.github.pagehelper.PageInfo;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/orders")
@Api(tags = "订单接口")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    RemoteSysUserService remoteSysUserService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    CouponsService couponsService;

    /**
     * 条件查询 订单分页接口
     * @param orders 订单对象
     * @return 分页结果对象 PageResult
     */
    @GetMapping("/page/{flag}")
    @ApiOperation("订单分页接口 -> 支持条件检索，检索条件封装在订单对象Orders中。如需分页，必传pageNum和pageSize")
    public PageResult page(Orders orders, @PathVariable int flag){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<Orders> ordersList;
        long allRecordNumber;
        if (flag == 0){ //查询全部记录
            try {
                ordersList = orderService.findOrdersList(orders);
                allRecordNumber = orderService.findAllRecordNumber();
                pageInfo = new PageInfo<>(ordersList);
            } catch (Exception e) {
                e.printStackTrace();
                return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
            }
        } else if (flag == 1) { //查询商品订单记录
            try {
                ordersList = orderService.findGoodsOrdersList(orders);
                allRecordNumber = orderService.findAllGoodsRecordNumber();
                pageInfo = new PageInfo<>(ordersList);
            } catch (Exception e) {
                e.printStackTrace();
                return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
            }
        }else { //查询优惠券订单记录
            try {
                SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
                if (!sysUser.isAdmin()){
                    return new PageResult(HttpStatusCode.ERROR,MessageConstant.NORMAL_STORE_CAN_NOT_GET_COUPONS_ORDERS);
                }
                ordersList = orderService.findCouponsOrdersList(orders);
                allRecordNumber = orderService.findAllCouponsRecordNumber();
                pageInfo = new PageInfo<>(ordersList);
            } catch (Exception e) {
                e.printStackTrace();
                return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
            }
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS, pageInfo.getTotal(), ordersList, allRecordNumber);
    }

    /**
     * 由订单ID获取订单信息
     * @param orderId 订单ID
     * @return 结果对象
     * @Author ChengLee
     * @Date 2023/05/04
     */
    @ApiOperation("由订单ID获取订单信息 -> 订单ID不可为空")
    @GetMapping("/orderById")
    public Result getOrderByOrderId(Long orderId){
        if (orderId == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        Orders byOrderId;
        try {
            byOrderId = orderService.findByOrderId(orderId);
            if (byOrderId == null){
                return new Result(HttpStatusCode.ERROR,MessageConstant.ORDER_NOT_EXIST);
            }
            UserInfo userInfo = userInfoService.findByUserId(byOrderId.getOrder_user_id());
            Map<String,Object> param = new HashMap<>();
            param.put("userName",userInfo.getReal_name());
            SysUser sysUserById = remoteSysUserService.getSysUserById(byOrderId.getStore_id());
            param.put("storeName",sysUserById.getNickName());
            if (byOrderId.getGoods_id() != null && byOrderId.getGoods_id() > 0){
                Goods goods = goodsService.findByGoods_id(byOrderId.getGoods_id());
                param.put("goodsName",goods.getGoods_name());
            }else {
                Coupons coupons = couponsService.findByCouponsId(byOrderId.getCoupons_id());
                param.put("couponsName",coupons.getCoupon_name());
            }
            byOrderId.setParams(param);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_ORDER_INFO_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_ORDER_INFO_SUCCESS,byOrderId);
    }


    /**
     * 新增订单
     * @param orders 订单对象
     * @return 结果对象 Result
     */
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("订单新增接口 -> 订单所属用户ID、商家ID、购买数量、订单状态、收货人姓名、收货人电话、收货地址、志愿者团支部分区不能为空，商品ID和优惠券ID不能全为空")
    public Result NewOrder(@RequestBody Orders orders){
        if (orders.getOrder_user_id() == null || orders.getStore_id() == null || orders.getNumber() == null || StringUtils.isBlank(orders.getVolunteer_area()) ||
            orders.getOrder_status() == null || orders.getConsignee_name() == null || orders.getConsignee_phone() == null ||
            orders.getConsignee_address() == null || (orders.getGoods_id() == null && orders.getCoupons_id() == null)){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            orderService.NewOrder(orders);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("商品库存不足！")){
                return new Result(HttpStatusCode.WARNING,MessageConstant.OUT_OF_GOODS_STOCK);
            } else if (e.getMessage().equals("优惠券库存不足！")) {
                return new Result(HttpStatusCode.WARNING,MessageConstant.OUT_OF_COUPONS_STOCK);
            } else if (e.getMessage().equals("该订单已不可取消！")) {
                return new Result(HttpStatusCode.WARNING, MessageConstant.CAN_NOT_CANCEL_ORDER);
            }else {
                return new Result(HttpStatusCode.ERROR,MessageConstant.SERVER_ERROR);
            }
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_ORDER_SUCCESS);
    }

    /**
     * 修改订单
     * @param orders 订单对象
     * @return 结果对象 Result
     */
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("订单修改接口 -> 订单ID、订单所属用户ID、商家ID、购买数量、订单状态、收货人姓名、收货人电话、收货地址不能为空，商品ID和优惠券ID不能全为空")
    public Result UpdateOrder(@RequestBody Orders orders){
        if (orders == null || orders.getOrder_id() == null || orders.getOrder_user_id() == null || orders.getStore_id() == null || orders.getNumber() == null ||
            orders.getOrder_status() == null || orders.getConsignee_name() == null || orders.getConsignee_phone() == null || orders.getConsignee_address() == null
            || (orders.getGoods_id() == null && orders.getCoupons_id() == null)){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            orderService.UpdateOrder(orders);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_ORDER_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_ORDER_SUCCESS);
    }

    /**
     * 根据订单ID取消订单
     * @param order_id 订单ID
     * @return 结果对象 Result
     */
    @Log(title = "订单管理", businessType = BusinessType.CANCEL)
    @DeleteMapping("/{order_id}")
    @ApiOperation("根据订单ID取消订单接口 -> path传订单ID")
    public Result CancelOrder(@PathVariable Long order_id){
        if (order_id == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            orderService.CancelOrder(order_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.CANCEL_ORDER_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.CANCEL_ORDER_SUCCESS);
    }

    /**
     * 导出订单信息到 Excel表格
     * @param response http响应
     * @param orders 订单对象
     */
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("订单信息Excel导出接口 -> 支持条件检索，检索条件封装在订单对象Orders中")
    public void export(HttpServletResponse response, Orders orders) {
        List<Orders> list = orderService.findOrdersList(orders);
        ExcelUtil<Orders> util = new ExcelUtil<>(Orders.class);
        util.exportExcel(response, list, "订单数据");
    }
}
